#!/bin/bash
#########################################################################
#
# File:         ngpull
# Description:  push perfdata of Nagios into ElasticSearch.
# Language:     GNU Bourne-Again SHell
# Version:      1.1.1
# Date:         2017-12-1
# Corp.:        liaoyichang
# Author:       atdmliaod@tom.com
#########################################################################

SOURCE="$( cd "$( dirname "$0"  )" && pwd  )"

PUSH_CMD=@tools@/nag2es
ES_SERVER=@es_server@

NG_DIR=$SOURCE
SOURCE_DIR=$NG_DIR/var/spool
REDO_DIR=$NG_DIR/var/recheck/
LOG_FILE=$NG_DIR/log/es

print_help_msg(){
        print_version
        $ECHO "Usage: $0 -h to get help."
        $ECHO
        $ECHO 'Report bugs to: liaoyq@tom.com'
}
print_full_help_msg(){
        print_version
        $ECHO "Usage:"
        $ECHO "$0  [ -h ]"
}
print_version(){
        $ECHO $(cat $0 | head -n 7 | tail -n 1|sed 's/\# //')
}

to_debug(){
                $ECHO "`date +'%Y-%m-%d:%H:%M:%S'`|$*"
}
to_debugn(){
                $ECHO -n "$*"
}
case "$(uname -s)"
        in
        SunOS)
        ECHO="echo"
        ;;
        Linux)
        ECHO="echo -e"
        ;;
        *)
        ECHO="echo"
        ;;
esac
if [ ! -x "$PUSH_CMD" ];then
        $ECHO "Can not found command $PUSH_CMD, pleas check it"
        exit 3
fi
if [ $# -gt 1 ]; then
    echo $$ > $1
fi

while :
do
if [ -f "$NG_DIR/var/liaoyq" ]; then
   break
fi

files=`ls $SOURCE_DIR`
for i in $files; do
  sdate=`date +'%Y-%m-%d'`
  log="$LOG_FILE-$sdate.log"
  tmp=`$PUSH_CMD -v 3 -l $log -s $ES_SERVER -c cp "$SOURCE_DIR/$i"|grep line|grep error |wc -l`

  if [ "$tmp" == "0" ]; then
#      $ECHO "process $i successful" >> $log
      rm -rf "$SOURCE_DIR/$i"
  else
     $ECHO "`date +'%Y-%m-%dT%H:%M:%S'` [ngpull:75] process $i error, move to re-check" >> $log
     $ECHO "`date +'%Y-%m-%dT%H:%M:%S'` : process $i error, move to re-check" 
      mv "$SOURCE_DIR/$i" $REDO_DIR
   fi
done
sleep 10
done

